package cn.gcjxsc.service.merchant;

import cn.gcjxsc.common.consts.PayChannel;
import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.consts.merchant.MerchantAccountType;
import cn.gcjxsc.data.recharge.RechargeData;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.entity.merchant.MerchantAccount;
import cn.gcjxsc.entity.merchant.recharge.RechargeRecord;
import cn.gcjxsc.repository.order.BaseOrderRepository;
import cn.gcjxsc.service.mall.OrderService;
import cn.gcjxsc.service.merchant.MerchantAccountService;
import cn.gcjxsc.service.merchant.recharge.RechargeRecordService;
import com.zgxl.common.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商户充值业务类.
 *
 * @author pumbaa
 * @since 1.0
 */
@Service("merchantRechargeService")
public class RechargeService {

    @Autowired
    private MerchantAccountService accountService;
    @Autowired
    private RechargeRecordService recordService;
    @Autowired
    private OrderService orderService;

    /**
     * 处理商户充值结果
     * @param merchant 商户信息
     * @param accountType 账户类型
     * @param data 充值数据
     */
    @Transactional
    public void doRecharge(Merchant merchant, MerchantAccountType accountType, RechargeData data, BaseOrder order) {
        long timestamp = System.currentTimeMillis()/1000;

        MerchantAccount account = accountService.findByMerchantIdAndType(merchant, accountType.getType());
        account.setAmount(account.getAmount().add(data.getAmount()));

        RechargeRecord record = new RechargeRecord();
        record.setOwnerId(merchant.getId());
        record.setAmount(data.getAmount());
        record.setChannel(data.getChannel());
        record.setOutTradeNo(data.getOutTradeNo());
        record.setCreated(DateTimeUtil.getTimestamp());
        record.setTradeNo(data.getTradeNo());
        record.setRemark(data.getRemark());
        record.setType(accountType.getType());

        order.setPayStatus(PayStatus.PAID);
        order.setPayChannel(PayChannel.fromName(data.getChannel()));
        order.setPayTime(timestamp);
        order.setDoneTime(timestamp);

        accountService.saveOrUpdate(account);
        recordService.saveOrUpdate(record);
        orderService.saveOrUpdate(order);
    }

    public List<RechargeRecord> findRechargeRecordList(){

        return null;
    }
}
